﻿Public Class FormCategory

    Private Sub FormCategory_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        UI.FormatDataGrid(Me.dgv)
        LoadData()
    End Sub
    Private Sub LoadData()
        Cmd.Parameters("@s") = txtSearch.Text
        Dim dt As DataTable = Cmd.ExecuteDataTable("SELECT Type.TypeName,Category.CategoryId,Category.CategoryName,Category.Active FROM Category INNER JOIN Type ON Category.CategoryId=Type.TypeId WHERE UPPER (CategoryName) LIKE UPPER('%'+@s+'%')")
        Me.dgv.DataSource = dt
    End Sub

    Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
        LoadData()
    End Sub

    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Dim frm As New FormCategoryEditor()
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            LoadData()
        End If
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        If Me.dgv.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Dim row = Me.dgv.SelectedRows(0)
        Dim frm As New FormCategoryEditor()
        frm.txtCategoryId.Text = row.Cells("CategoryId").Value
        frm.txtCategoryName.Text = row.Cells("CategoryName").Value
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            LoadData()
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Me.dgv.SelectedRows.Count = 0 Then
            Exit Sub
        End If

        If MessageBox.Show("Are you sure want to delete ?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) <> Windows.Forms.DialogResult.Yes Then
            Exit Sub
        End If
        Dim row = Me.dgv.SelectedRows(0)
        Dim id = row.Cells("CategoryId").Value


        Cmd.Parameters("@CategoryId") = id
        Cmd.ExecuteNonQuery("UPDATE Category SET Active=0 WHERE CategoryId=@CategoryId")

        LoadData()
    End Sub
End Class